/*
 * @author klv
 */
var QS_BaseSearch={
	selectedItem:{},
	keyWordCode:"OS01W",
	indexColKey:Search_DefaultData["search_DataKey"].join('_'),
	tickerCode:"OS001",
	PIdCode:"OS06Y",
	SIdCode:"OS00I",
    specialChars:["AND","OR"],//["AND","OR","+","-","&&","||","!","(",")","{","}","[","]","^","~","*",":","\\"]
    screenerWidgetType:25,
	templeteType:"51",//screener list
	replaceKeyWordCode:"sOS01W",
	securityTypeCode:"OS010",
	selectedCategory:{range:[],option:[]},//temp availible
	baseSearchInit:function(){
		if(Search_DefaultData.share){
            $.extend(true,Search_DefaultData.selectableSearchDetail,this.searchField);
		}
		if(this.codeMap){
			for(var code in this.codeMap){
				if(!Search_DefaultData.selectableSearchDetail[code]){//AC013 to OS010
					var mscode=this.codeMap[code];
					Search_DefaultData.selectableSearchDetail[code]=$.extend(true,{},Search_DefaultData.selectableSearchDetail[mscode],{val:code});
				}
			}
		}
	},
    checkSpecialCharacters:function(selecters){
        var newSelecters=[];
        for(var i=0,l=selecters.length;i<l;i++){
            newSelecters[i]=this._checkSpecialChar(selecters[i]);
        }
        return newSelecters;
    },
    _checkSpecialChar:function(charstr){
        if($.inArray(charstr,this.specialChars)>-1){
            return "\\"+charstr;
        }else{
            return charstr;
        }
    },
    checkPermission:function(code){
        var dataitem = Search_DefaultData.selectableSearchDetail[code];
        if(typeof dataitem["permission"]!="undefined"&&!dataitem["permission"]){
            return false;
        }
        return true;
    },
	getFixedData:function(vals){
		this.selectedCategory={range:[],option:[]};
        var temp=Search_DefaultData.selectableSearchDetail,code=null,detailItem=null,tempTxt=null;
        for (var j = 0, m = vals.length; j < m; j++) {
			code=vals[j],detailItem=this._getFieldProperties(code);
            if(typeof detailItem["permission"]!="undefined"&&!detailItem["permission"]) continue;
            if (!this.selectedItem[code]) {
				this.selectedItem[code]={};
				this._setCategory(detailItem);
				tempTxt=detailItem.txt;
				$.extend(true,this.selectedItem[code],detailItem,{"view":detailItem.view||tempTxt,"renderer":detailItem.renderer||null});
            }
        }
		return this.selectedItem;
    },
	clearSelectedItem:function(){
		var temp=null;
		for (var code in this.selectedItem) {
			temp=this.selectedItem[code]["renderType"];
			switch (temp) {
				case "sld":
				case "str":
					delete this.selectedItem[code];
					break;
				default:
					break;
			}
		}
	},
	getCode:function(code){
	    return this.codeMap&&this.codeMap[code]?this.codeMap[code]:code;
	},
	getPidBySavedData:function(selectedData,top,col,sortfield,sorttype,callback){
        var top=top||20;
        if(sortfield==this.keyWordCode) sortfield=this.replaceKeyWordCode;
        this.getFixedData(selectedData.items);
		this.curTabID=selectedData.tabID;
        var globequery=this._getDefaultFilterForDynamicData();
        for(var code in selectedData.selected){
            var temp=selectedData.selected[code];
            if (this._isEmptyArray(temp))
                continue;
            globequery['Keywords'].push(this._addfilter(code, $.extend(true,{},this.selectedItem[code],{selected:temp})));
        }
        var args={
            type: "ticker",
            start: "0",
            count: top,
            operator: "AND",
            query: $.toJSON(globequery),
            col: $.toJSON({
                Columns: col||['OS06Y']
            })
        };
        if(sortfield){
            args.sortfield = sortfield;
            args.sorttype = sorttype;
        }else if (selectedData.sortfield) {
            args.sortfield = selectedData.sortfield;
            args.sorttype = selectedData.type;
        }
        DBHelper.getSearchResult(args,function(o){
            if (o=="error"){
                o = {};o.Columns = [];
            }else{
                o=$.evalJSON(o);
            }
            callback(o);
        });
    },
	getDynamicData:function(vals,successsCB,failureCB){
        this.getFixedData(vals);
        var category=this.selectedCategory;
		var self=this;
		
        var flag=0,SYNC=2;
        if (category.option.length > 0) {
            DBHelper.getOptionsByCode(category.option, function(data){
                flag++;
				if (data != "error") {
					var temp = null, options = $.evalJSON(data);
					for (var i = 0, l = options.Fields.length; i < l; i++) {
						temp = options.Fields[i];
						self._setSelectedPower(self.selectedItem[temp.Code].renderType, temp);
						self.selectedItem[temp.Code].selectable = temp.Option;
					}
					if (typeof successsCB == 'function' && flag == SYNC) {
	                    successsCB(self.selectedItem);
	                }
				}else{
					if (typeof failureCB == 'function') {
                        failureCB();
                    }
				}
            });
        }else{
			flag++;
		}
        if (category.range.length > 0) {
            this.getRangeByCode(category.range, function(data){
                flag++;
				if (data != "error") {
					var temp = null, ranges = $.evalJSON(data);
					for (var i = 0, l = ranges.field.length; i < l; i++) {
						temp = ranges.field[i];
						self.selectedItem[temp.code].selectable = {
							max: temp.max,
							min: temp.min
						};
					}
					if (typeof successsCB == 'function' && flag == SYNC) {
						successsCB(self.selectedItem);
					}
				}else{
                    if (typeof failureCB == 'function') {
                        failureCB();
                    }
                }
            });
        }else{
			flag++;
		}
		if(flag == SYNC){
			successsCB(this.selectedItem);
		}
    },
	getSearchResult:function(callback,start,count,cols,sortfield,sorttype){
        //operator
        if(sortfield==this.keyWordCode) sortfield=this.replaceKeyWordCode;//fix don't support sort by name
        var self=this,globequery=this._getQueryCondition();
        //sortField:sortField, sortType:sortType
        if (globequery.query['Keywords'].length == 0 && this.curTabID == "ALL") {
            Util.message(QS_Lang.screener.needcriterion);
            if (typeof callback == 'function') {
                callback([],0,true);
            }
        }
        else {
            var searchData={
                type: "ticker",
                start: start||"0",
                count: count||"100",
                operator: "AND",
                query: $.toJSON(globequery.query),
				col: $.toJSON({
                    Columns: cols||globequery.cols
                    })
            };
            if(sortfield){
                searchData["sortfield"]=sortfield;
            }
            if(sorttype){
                searchData["sorttype"]=sorttype;
            }
			var viewCol=self.getViewCols(cols||globequery.cols);
            DBHelper.getSearchResult(searchData, function(o){
                //alert(o);
				if (o == "error") {
					Util.message(QS_Lang.screener.searchfailed);
					callback([],0);
				}else {
					if ($.trim(o) == "") {
						o = {Columns:[],Count:0};
					}else {
						o = $.evalJSON(o);
					}
					if (typeof callback == 'function') {
						var dataKeyList=Search_DefaultData["search_DataKey"],dataKey=self.indexColKey;
						for (var j = 0, m = o.Columns.length; j < m; j++) {
							o.Columns[j][dataKey] = String.format("{0}_{1}_{2}_{3}", o.Columns[j][dataKeyList[0]], o.Columns[j][dataKeyList[1]], o.Columns[j][dataKeyList[2]], o.Columns[j][dataKeyList[3]]);
							for (var i = 0, l = viewCol.length; i < l; i++) {
								var data = viewCol[i];
								if (data.renderType && data.renderType != 'msb' && data.renderType != 'ipt' && data.renderType != 'sld' && data.renderType != 'str') {
									o.Columns[j][data.dataIndex] = self._getValueFromOption(data.dataIndex, o.Columns[j][data.dataIndex]);
								}
								else 
									if (data.renderType == 'sld') {
										if ($.trim(o.Columns[j][data.dataIndex]) == "NaN") {
											o.Columns[j][data.dataIndex] = "--";
										}
									}
							}
						}
						callback(o.Columns,o.Count);
					}
				}
            });
        }
    },
	_getQueryCondition:function(){
        var cols=[],deleteCol=[],temp=this.filters[this.securityTypeCode],defaultQuery=this._getDefaultFilterForDynamicData(),globeQuery={'Keywords':[]};
		if (defaultQuery['SecType']||(temp&&temp.selected.length==1)) {//SecType
            globeQuery['SecType'] = defaultQuery['SecType']||temp.selected[0];
        }
		for (var code in this.filters) {
            temp = this.filters[code];
			cols.push(code);
            if (this._isEmptyArray(temp.selected)) {
				continue;
			}
			deleteCol.push(code);
            globeQuery['Keywords'].push(this._addfilter(code,temp));
        }
		for(var i=defaultQuery["Keywords"].length-1;i>=0;i--){
			temp=defaultQuery["Keywords"][i].Name;
			if($.inArray(temp,deleteCol)==-1){
				globeQuery['Keywords'].unshift(defaultQuery["Keywords"][i]);
			}
		}
        return {query:globeQuery,cols:cols};
    },
	clearSelectedItemValue:function(){
		var filter=null;
		for(var code in this.filters){
			filter=this.filters[code];
			if (filter.status != "fix") {
				filter.selected = [];
			}
		}
	},
	_getFilterData:function(){
		var data = {tabID:this.curTabID,items:[],selected:{}},tempCate=null,msCode;
        for (var code in this.filters) {
			msCode=this.getCode(code);//need to convert to local code
            data.items.push(msCode),tempCate=this.filters[code];
            if(!this._isEmptyArray(tempCate.selected)){
                data.selected[msCode] = tempCate.selected;
            }
        }
		return data;
	},
	getDynamicCode:function(){
		var tempCate=null,data=[];
		for(var code in this.filters){
			tempCate=this.filters[code];
			if(tempCate.status!="fix"){
				data.push(this.getCode(code));//have been converted to local code
			}
		}
		return data;
	},
	getSavedData:function(){
        var data=this._getFilterData();
        if(this.curTabID == "ALL" && $.isEmptyObject(data.selected)){
            Util.message(QS_Lang.screener.needcriterion);
            return {cansave:false,"data":data};
        }
        return {cansave:true,"data":data};
    },
	getViewCols:function(cols){
        var tempDataDetail = null,gridcol=[],code=null,codeMap={};
        for (var i=0,l=cols.length;i<l;i++) {
			code=cols[i];
			if(codeMap[code]||!this.checkPermission(code)){continue;}
			codeMap[code]=true;
            tempDataDetail = this.selectedItem[code];
            gridcol.push({
                header: tempDataDetail.view,
                dataIndex: code,
                width: tempDataDetail.w,
                dataType :tempDataDetail.t,
                className :"custom-grid-cell-"+code,
                renderer: tempDataDetail.renderer,
                align: tempDataDetail.a||'right',
                renderType: tempDataDetail.renderType,
                ellipsis:tempDataDetail.ellipsis||false
            });
        }
        return gridcol;
    },
	_setSelectedPower:function(rendertype,data){
        switch(rendertype){
            case 'rbl':
                this._filterNAItem(data.Option);//filter NA item
                break;
            case 'cbl':
                this._filterItem(data.Code,data.Option);
                break;
            default:
                break;
        }
    },
	_filterItem:function(code,option){
        var specialconfig=this.searchScoreConfig,filterlist=null;
		if(!specialconfig) return;
		filterlist=specialconfig[code];
        if(filterlist&&((!filterlist.universe)||filterlist.universe==this.curTabID)){
            this.selectedItem[code].renderType=filterlist.renderType;
            var temp=null;
            for (var m = option.length,j = m-1;j>=0; j--) {
                 temp=option[j];
                 var tag=false,specialSel=null;
                 for (var i = 0, l = filterlist.selected.length; i < l; i++) {
                    specialSel = filterlist.selected[i];
                    if (temp.val == specialSel) {
                        tag = true;
                        break;
                    }
                 }
                 if(!tag){
                    option.splice(j, 1);
                }
            }
        }
    },
	_filterNAItem:function(data){
        for(var l=data.length,i=l-1;i>0;i--){
            var temp=data[i];
            if(temp.val=='NA'){
                data.splice(i, 1);
                return;
            }
        }
    },
	_isEmptyArray:function(array){
        if(array.length==0) return true;
        var i=0;
        for(i=0,l=array.length;i<l;i++){
            if($.trim(String(array[i])).length>0) return false;
        }
        if(i==array.length) return true;
    },
	_setCategory:function(item){
		var detailItem=item;
		switch(detailItem.renderType){
			case "msb"://style box
			case "cbl":
			case "dpl":
			case "rbl":
                this.selectedCategory.option.push(detailItem.val);
                break;
			case "sld":
			case "str":
				this.selectedCategory.range.push(detailItem.val);
				break;
			default:
                break;
		}
	},
	_getValueFromOption:function(code,value){
        var temp=this.selectedItem[code].selectable;
		
        for(var i=0,l=temp.length;i<l;i++){
            if(temp[i].val==value){
                return temp[i].txt;
            }
        }
        return value;
    },
    _getFieldProperties:function(code){
        if(Search_DefaultData.share){
            this._getFieldProperties=function(code){
                return Search_DefaultData.selectableSearchDetail[code];
            }
        }else{
            this._getFieldProperties=function(code){
                var returnValue= Search_DefaultData.selectableSearchDetail[code],searchFieldItem=this.searchField[code];
                if(searchFieldItem){
                    returnValue = $.extend(true,{},returnValue,searchFieldItem);
                }
                return returnValue;
            }
        }
        return this._getFieldProperties(code);
    },
	getRangeByCode:function(vals,callback){
		//type:advanced,option
        DBHelper.getRangeByCode({query:this._getDefaultFilterForDynamicData(),fields:vals},callback);
	},
	_getDefaultFilterForDynamicData:function(){
		var defaultQuery = {
			Keywords: this._getDefaultFilter().slice(0)
		};
		if(this.curTabID!="ALL"){
			defaultQuery.SecType=this.curTabID;
			defaultQuery.Keywords.push(this._getSecurityTypeFilter());
		}
		return defaultQuery;
    },
	_getDefaultFilter:function(){//only cache default search condition
		if (!this.cacheDefaultFilter){
            this.cacheDefaultFilter={};
        }
        if(!this.cacheDefaultFilter[this.curTabID]) {
            this.cacheDefaultFilter[this.curTabID]=[];
        	if (this.searchScoreConfig) {
        		var specialfilter = null;
        		for (var code in this.searchScoreConfig) {
        			specialfilter = this.searchScoreConfig[code];
        			if ((!specialfilter.universe) || specialfilter.universe == this.curTabID) {
        				this.cacheDefaultFilter[this.curTabID].push(this._addfilter(code, specialfilter));
        			}
        		}
        	}
		}
		return this.cacheDefaultFilter[this.curTabID];
	},
	_getSecurityTypeFilter:function(){
		return {Name: this.securityTypeCode,Type: 1,TextOperator: 1,Value: this.curTabID};
	},
	_addfilter:function(code,data){
        var returnValue={};
        returnValue.Name=code;
		
        switch(data.renderType){
            case 'ipt':
                returnValue.Type=1//1:equals/2:between/3:in
                returnValue.TextOperator=2//1:exact/2:startwith
                returnValue.Value=data.selected[0];
                break;
            case 'sld':
                returnValue.Type=2;
                returnValue.IsInclude = true; 
                var min=data.selected[0],max=data.selected[1];
                returnValue.MinValue=data.selectable?Math.max(data.selectable.min,min):min;
                returnValue.MaxValue=data.selectable?Math.min(data.selectable.max,max):max;
                break;
            case 'str':
            case 'msb':
            case 'dpl':
            case 'cbl':
            case 'rbl':
                returnValue.Type=3;
                returnValue.IsInclude = true;
                returnValue.TextOperator=1;//code=='OS01V'?2:1;
                returnValue.Value=this.checkSpecialCharacters(data.selected).join(',');
                break;
            default:
                break;
        }
        return returnValue;
    }
};
